<%@page import="java.util.LinkedHashMap"%>
<%@page import="fr.inserm.u674.chcdbweb.model.DTO.Tissue"%>
<%@ taglib prefix="ccc" uri="http://bibeault.org/tld/ccc" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="extraction" tagdir="/WEB-INF/tags/tissueExtractionTags" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Variable List</title>

<jsp:include page="includes/header.jsp"></jsp:include>
<script type="text/javascript" src="scripts/gridCommon.js"></script>
<script type="text/javascript" src="scripts/common.js"></script>

<!-- DHTMLXWINDOWS -->
<link rel="STYLESHEET" type="text/css" href="scripts/dhtmlxwindows-codebase/dhtmlxwindows.css">
<link rel="STYLESHEET" type="text/css" href="scripts/dhtmlxwindows-codebase/skins/dhtmlxwindows_dhx_skyblue.css">
<script type="text/javascript" src="scripts/dhtmlxwindows-codebase/dhtmlxcontainer.js" ></script>
<script type="text/javascript" src="scripts/dhtmlxwindows-codebase/dhtmlxcommon.js" ></script>
<script type="text/javascript" src="scripts/dhtmlxwindows-codebase/dhtmlxwindows.js" ></script>

<!-- DHTMLXGRID -->
<link rel="STYLESHEET" type="text/css" href="scripts/dhtmlxgrid-codebase/dhtmlxgrid.css">
<link rel="STYLESHEET" type="text/css" href="scripts/dhtmlxgrid-codebase/skins/dhtmlxgrid_dhx_skyblue.css">
<link rel="STYLESHEET" type="text/css" href="scripts/dhtmlxgrid-codebase/skins/dhtmlxgrid_dhx_black.css">
<link rel="STYLESHEET" type="text/css" href="scripts/dhtmlxgrid-codebase/skins/dhtmlxgrid_dhx_blue.css">
<script src="scripts/dhtmlxgrid-codebase/dhtmlxcommon.js"></script>
<script src="scripts/dhtmlxgrid-codebase/dhtmlxgrid.js"></script>
<script src="scripts/dhtmlxgrid-codebase/dhtmlxgridcell.js"></script>
<script src="scripts/dhtmlxgrid-codebase/ext/dhtmlxgrid_srnd.js"></script>
<script src="scripts/dhtmlxgrid-codebase/ext/dhtmlxgrid_selection.js"></script>
<script src="scripts/dhtmlxgrid-codebase/ext/dhtmlxgrid_filter.js"></script>
<script src="scripts/dhtmlxgrid-codebase/ext/dhtmlxgrid_nxml.js"></script>

<!-- DTHMLXDATAPROCESSOR -->
<script  src="scripts/dhtmlxdataprocessor-codebase/dhtmlxdataprocessor.js"></script>
<script  src="scripts/dhtmlxdataprocessor-codebase/dhtmlxdataprocessor_debug.js"></script>

<!-- DHTMLXCALENDAR -->
<script type="text/javascript">
window.dhx_globalImgPath = "scripts/dhtmlxcalendar-codebase/imgs/";
</script>
<script type="text/javascript" src="scripts/dhtmlxcalendar-codebase/dhtmlxcalendar.js" ></script>
<link rel="STYLESHEET" type="text/css" href="scripts/dhtmlxcalendar-codebase/dhtmlxcalendar.css">



<script type="text/javascript" >

	var grid;
	var modalityGrid;
	var cal;
	
	var dp;
	
	
	
	function initCal(){
		cal =  new dhtmlxCalendarObject(
				"creationDate", 
				true, {isYearEditable: true }
				);
	    cal.options.weekstart = 1;
	}

	function doInitWin(){
	    dhxWins = new dhtmlXWindows();
	    dhxWins.enableAutoViewport(true);
	    dhxWins.setImagePath("scripts/dhtmlxwindows-codebase/imgs/");
	}
	
	function doInitGrid(){
		grid = new dhtmlXGridObject('gridContainer');
		grid.setHeader("Full Name,Name,Data Type,Creation Date,Deprecated Variable,Description");
		grid.setColumnIds("variableName,humanReadableName,dataType,creationDate,deprecatedVariable,description");
		grid.setInitWidths("330,100,80,80,*,450");
		grid.setColSorting("str,str,str,str,str,str");
		grid.attachHeader("#text_filter,#text_filter,#select_filter,#text_filter,#select_filter,#text_filter");

		grid.enableSmartRendering(false);
		grid.enableAutoHeight(false);
		grid.setEditable(false);
		
		commonGridInit(grid);
		
		grid.attachEvent("onRowSelect", function(id,ind){
			doDisplayVariable(id);
		});
		
		grid.init();
	}
	
	function doFillGrid() {
		new Ajax.Request('mainServlet',{
			method: 'post',
			parameters: {appAction: 'ajaxListVars'},
			onSuccess: function(transport){
				grid.parse(transport.responseText);
				hideGridSpinnerAndShowGridContainer();
			},
			onFailure : function(transport){
				handleErrorResponseWindow(transport.responseText); //cf. common.js
			}
		}
		);
	}
	
	function doInitModalityGrid(){
		
		modalityGrid = new dhtmlXGridObject('modalityGridContainer');
		modalityGrid.setHeader("Modality,Number of occurences");
		modalityGrid.setColumnIds("modality,nOccurences");
		modalityGrid.setInitWidths("350,100");
		modalityGrid.setColSorting("str,int");
		
		commonGridInit(modalityGrid);
		
		/* modalityGrid.attachEvent("onRowSelect", function(id,ind){
			doDisplayModality(id);
		}); */
		
		
		modalityGrid.init();
	}
	
	function doFillModalityGrid(eavVariableID){
		modalityGrid.clearAll();
		new Ajax.Request('mainServlet',{
			method: 'POST',
			parameters: {
				appAction: 'ajaxLoadModalityGridAndModalityList',
				eavVariableID: eavVariableID 
			},
			onSuccess: function(transport){
				var jsonResponse = transport.responseText;
				var array = jsonResponse.evalJSON();
				
				//filling the modality grid
				modalityGrid.parse(array[1]);
				
				//filling the curation old modalities select 
				var modalitiesHash = new Hash(array[0].evalJSON());
				var optionString = "";
				for(var i=0;i<modalitiesHash.keys().size();i++){
					optionString = optionString + "<option>"+modalitiesHash.keys()[i]+"</option>";
				}
				$('oldModalityValue').update(optionString);
				
			},
			onFailure : function(transport){
				handleErrorResponseWindow(transport.responseText); //cf. common.js
			}
		});
	}

	function loadOldModalities(eavVariableID){
		new Ajax.Request('mainServlet',{
			method: 'POST',
			parameters: {
				appAction: 'ajaxLoadOldModalities',
				eavVariableID: eavVariableID
			},
			onFailure : function(transport){
				handleErrorResponseWindow(transport.responseText); //cf. common.js
			},
			onSuccess: function(transport){
				var modalitiesList = transport.responseText.evalJSON();
				var optionString = "";
				for(var i=0;i<modalitiesList.size();i++){
					optionString = optionString + "<option>"+modalitiesList[i]+"</option>";
				}
				$('oldModalityValue').update(optionString);
			}
		});
	}
	
	function doDisplayVariable(eavVariableID){

		hideNewVarForm();
		
		new Ajax.Request('mainServlet',{
			method: 'POST',
			parameters: {
				appAction : 'ajaxFetchVar',
				eavVariableID: eavVariableID
			},
			onSuccess: function(transport){
				eavVariable = transport.responseText.evalJSON();
				$('variableName').setValue(eavVariable.variableName);
				$('humanReadableName').setValue(eavVariable.humanReadableName);
				
				$('dataType').setValue(eavVariable.dataType );
				
				if(eavVariable.deprecated)
					$('isDeprecated').setValue('YES');
				else
					$('isDeprecated').setValue('NO');
				$('description').setValue(eavVariable.description);
				$('variableID').setValue(eavVariable.variableID);
				var creationDate = new Date(eavVariable.creationDate);
				var month = creationDate.getMonth()+1;
				if(month<10)
					month = '0'+month;
				var day = creationDate.getDate();
				if(day < 10)
					day = '0' + day;
				var year = creationDate.getFullYear();
				$('creationDate').setValue(year+'-'+month+'-'+day);
				
				$('variableNameCur').setValue(eavVariable.variableName);
				$('varID').setValue(eavVariableID);
				//loadOldModalities(eavVariableID);
				
				
				doFillModalityGrid(eavVariableID);
			},
			onFailure : function(transport){
				handleErrorResponseWindow(transport.responseText); //cf. common.js
			}
		});
	}
	
	function doUpdateSelectedVariable(){
		var varToUpdate = {};
		varToUpdate.variableID = $('variableID').getValue();
		varToUpdate.variableName = $('variableName').getValue();
		varToUpdate.humanReadableName = $('humanReadableName').getValue();
		varToUpdate.description = $('description').getValue();
		var dataType = $('dataType').getValue();
		
		varToUpdate.dataType = dataType;
		
		varToUpdate.deprecated = ($('isDeprecated').getValue()=='YES');
		varToUpdate.creationDate = $('creationDate').getValue();
		
		new Ajax.Request('mainServlet',{
			method: 'POST',
			parameters: {
				appAction: 'ajaxUpdateEAVVariable',
				varToUpdateJSON : Object.toJSON(varToUpdate)
			},
			onFailure: function(transport){
				handleErrorResponseWindow(transport.responseText); //cf. common.js
			},
			onSuccess: function(transport){
				dhtmlxgridUpdateString = transport.responseText;
				doInitGrid();
				doFillGrid();
				alert('Variable '+varToUpdate.variableName+' successfully updated !');
			}
		});
	}
	
	
	function doSubmitVariable(){
		
		new Ajax.Request('mainServlet',{
			method:'POST',
			parameters: {
				appAction: 'ajaxSubmitVar',
				variableName : $F('variableName'),
				humanReadableName : $F('humanReadableName'),
				dataType : $F('dataType'),
				isDeprecated : $F('isDeprecated'),
				description : $F('description'),
				creationDate: $F('creationDate')
			},
			onSuccess: function(transport){
				var newVar = transport.responseText.evalJSON();
				//var creationDate = new Date(newVar.creationDate);	
				grid.addRow(
						newVar.variableID,
						[newVar.variableName,
						newVar.humanReadableName,
						newVar.dataType,
						formatDate(newVar.creationDate),
						'NO',
						newVar.description]
				);
				alert('New variable '+ newVar.variableName +' successfully created !');
				$('varInfoForm').reset();
				//$('variableName').focus();
			},
			onFailure: function(transport){
				handleErrorResponseWindow(transport.responseText); //cf. common.js
			}
		}
		);
	}
	
	
	function doDeleteVariable(){
		if($('variableID').getValue() == null || $('variableID').getValue() == ""){
			alert("No variable selected.");
		}
		else{
			var reallyDelete = confirm("Are you sure you want to delete this variable ? "+
				"This cannot be undone (It is usually better to mark the variable as deprecated).");
			if(reallyDelete){
				new Ajax.Request('mainServlet',{
					method: 'post',
					parameters: {
						appAction: 'ajaxDeleteVars',
						varsToDelete: $('variableID').getValue()
					},
					onFailure: function(transport){
						handleErrorResponseWindow(transport.responseText); //cf. common.js
					},
					onSuccess: function(transport){
						var resultVarList = transport.responseText.evalJSON();
						for (var i=0;i<resultVarList.length;i++){
							grid.deleteRow(resultVarList[i].variableID);
						}
					}
					
				});
			}
		}
	}
	
	function replaceModalities(){
		
		var oldModalityValue = $('oldModalityValue').getValue();
		var newModalityValue = $('newModalityValue').getValue().trim();
		var variableName = $('variableNameCur').getValue();
		
		if(newModalityValue== null || newModalityValue==''){
			alert('No new modality specified !!');
		}
		else{
			var question = "You are about to replace ALL the modalities with value '"+
							oldModalityValue+"' with the new value '"+newModalityValue+
							"' for the variable '"+variableName+"'";
			if(confirm(question)){
				new Ajax.Request('mainServlet',{
					method: 'post',
					parameters:{
						appAction: 'ajaxUpdateModalityByVariableNameAndModalityValue',
						variableName: variableName,
						oldModalityValue: oldModalityValue,
						newModalityValue: newModalityValue
					},
					onFailure: function(transport){
						handleErrorResponseWindow(transport.responseText); //cf. common.js
					},
					onSuccess: function(transport){
						var modifiedRows = transport.responseText;
						$('newModalityValue').setValue('');
						doDisplayVariable($('varID').getValue());
						alert(modifiedRows+' modalities were successfully modified !');
						
					}
						
				});
			}
		}
	}
	
	function showNewVarForm(){

		$('hideNewVarFormButton').show();		
		$('showNewVarFormButton').hide();
		
		$('varInfoLegend').update('New Variable Info');
		$('saveNewVarButton').show();
		$('updateButton').hide();
		$('deleteButton').hide();
		$('modalityGridContainer').hide();
		$('varInfoFieldSet');
		
		
		$('variableName').setValue('New_Variable_Name');
		$('humanReadableName').setValue('Variable Short Name');
		var currentDate = new Date();
		var year = currentDate.getFullYear();
		var day = currentDate.getDate();
		if(day<10)
			day = '0'  + day;
		var month = currentDate.getMonth()+1;
		if(month<10)
			month = '0' + month; 
		$('creationDate').setValue(year+'-'+month+'-'+day);
	}
	
	function hideNewVarForm(){
		$('hideNewVarFormButton').hide();		
		$('showNewVarFormButton').show();
		
		$('varInfoForm').reset();
		$('varInfoLegend').update('Variable Info');

		$('updateButton').show();
		$('deleteButton').show();
		$('modalityGridContainer').show();
		$('saveNewVarButton').hide();
	}
	
	function initPage(){
		$('hideNewVarFormButton').hide();
		$('saveNewVarButton').hide();
		doGrid();
		doInitWin();
		doInitModalityGrid();
		initCal();
	}
	

</script>


<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body onload=" initPage();">

<div id="container">
<div id="top">
<h1>CHC DB Web</h1>
</div>
<div id="leftnav"><jsp:include page="./includes/leftnav.jsp"></jsp:include></div>
<div id="content" >
<h2>Variables List</h2>



<fieldset><legend>Variable list</legend>
<div id="wholeContainer" style="width:1000;height:auto;">
	<div  align="center" id="gridSpinner" style="position: relative;top:45%;" >
		<img src="./images/ajax-loader-1.gif"/>
	</div>
	<div id="gridContainer" style="width:1000;height:700px;">
	</div>
</div>
</fieldset>
<br/>
<!-- <form > -->
<input id="showNewVarFormButton" type="button" value="Show new variable form" onClick="showNewVarForm();"/>
<input id="hideNewVarFormButton" type="button" value="Hide new variable form" onClick="hideNewVarForm();"/>
<!-- </form> -->
<br/>	
<fieldset id="varInfoFieldSet" ><legend id='varInfoLegend'>Variable Info</legend>
<form id="varInfoForm">
<input type="hidden" id="variableID"/>
<table>
<tr><td>Full Name :</td><td><input id="variableName" type="text" size="60" maxlength="80"></td></tr>
<tr><td>Name :</td><td><input id="humanReadableName" type="text" size="60" maxlength="80"></td></tr>
<tr><td>Data Type :</td><td><select id="dataType">
							<option >BOOLEAN</option>
							<option >DATE</option>
							<option >FLOAT</option>
							<option >INT</option>
							<option >VARCHAR</option>
							</select>
						</td></tr>
<tr><td>Creation Date :</td><td><input id="creationDate" type="text" readonly="readonly"></td></tr>
<tr><td>Deprecated :</td><td><select id="isDeprecated">
							<option >NO</option>
							<option >YES</option>
							</select>
						</td></tr>
						
<tr><td>Description :</td><td><textarea id="description"  cols="60" rows="5"></textarea></td></tr>
<tr><td>Modalities :</td><td><div id="modalityGridContainer" style="width:450px; height:200px;"></div></td></tr>
<tr>
<td></td>
<td>
<input id="updateButton" type="button" value="Update variable" onClick="doUpdateSelectedVariable();">
<input id="deleteButton" type="button" value="Delete variable" onClick="doDeleteVariable();">
<input id="saveNewVarButton" type="button" value="Save new variable" onClick="doSubmitVariable();">
</td>
</tr>
</table>

</form>
</fieldset>
<br/>
<fieldset id="varCurationFieldSet"><legend>Variable Curation</legend>
<!-- <form id="varCurationForm"> -->
<table>
<tr>
<td>Variable Full Name : </td><td>
	<input type="text" id="variableNameCur" size="60"  readonly="readonly"/></td>
<!-- 	<select id="variableNamesList"></select> -->
</tr>
<tr>
<td>Old modality :</td><td>
	<select id="oldModalityValue" >
	</select></td>
</tr>
<tr>
<td>New modality :</td><td><input type="text" id="newModalityValue" size="60" maxlength="255"/></td>
</tr>
<tr>
	<td><input type="hidden" id="varID"/>
	<input type="button" value="REPLACE MODALITIES" onClick="replaceModalities();"/></td>
</tr>
</table>
<!-- </form> -->
</fieldset>
</div>
<div id="footer"><jsp:include page="./includes/footer.jsp"/></div>
</div>
</html>